<template>
  <!-- 实测预报右侧父组件 -->
  <div class="lai-water-box">
    <div class="pre-box">
      <div class="title-box">
        <span>来水预报方案信息</span>
        <div class="title-search-box">
          <span>方案名称：</span>
          <el-input v-model="state.searchName" placeholder="请输入" style="width: 200px" />
          <el-button type="primary" @click="handleSearch()">查询</el-button>
        </div>
        <div class="title-right">
          <el-button type="primary" @click="handleLaishui()">新建</el-button>
          <!-- 按钮触发对话框 -->
          <el-button type="primary" @click="handleClickErrorSet">错误重启设置</el-button>
        </div>

        <!-- 对话框 -->
        <el-dialog title="错误重启设置" v-model="dialogVisible" width="30%" left>
          <el-form :model="form" label-width="120px">
            <!-- 发生错误重启 单选 是 否 -->
            <el-form-item label="发生错误重启">
              <el-radio-group v-model="form.restartOnError">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>

            <!-- 重启间隔时间 -->
            <el-form-item label="重启间隔时间(秒)">
              <el-input v-model.number="form.restartInterval" placeholder="秒"></el-input>
            </el-form-item>

            <!-- 重启次数 -->
            <el-form-item label="重启次数（次）">
              <el-input v-model.number="form.restartCount" placeholder="次"></el-input>
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="handleSaveErrorSet">确 定</el-button>
          </span>
        </el-dialog>
      </div>
      <el-table
        ref="tableRef"
        :data="state.schemeList"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column align="center" label="单选" width="60">
          <template #default="scope">
            <el-radio v-model="state.radio1" :label="scope.row.id">{{ '' }}</el-radio>
          </template>
        </el-table-column>

        <el-table-column
          prop="scName"
          label="方案名称"
          align="center"
          show-overflow-tooltip
          class="left-font"
        />
        <el-table-column
          prop="createType"
          label="创建类型"
          align="center"
          show-overflow-tooltip
          class="left-font"
        />
        <el-table-column prop="reportType" label="方案类型" align="center" show-overflow-tooltip />
        <el-table-column
          prop="yrPerd"
          label="预热期"
          align="center"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column
          prop="yjPerd"
          label="预见期"
          align="center"
          show-overflow-tooltip
          width="80"
        />
        <el-table-column prop="fcTime" label="预报时间" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <div :class="[switchStatusBg(row.status)]">{{ switchStatus(row.status) }}</div>
            <!-- {{ switchStatus(row.status) }} -->
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180" fixed="right">
          <template #default="scope">
            <div class="handle-box">
              <font
                v-if="scope.row.status != 1"
                :class="['iconfont', scope.row.status == 2 ? 'finish' : 'notStart']"
                title="计算"
                @click="handleCompute(scope.row, scope.$index)"
                >&#xe609;</font
              >
              <font v-if="scope.row.status == 1" :class="['iconfont']" title="计算中"
                >&#xe629;</font
              >
              <font
                v-if="scope.row.status == 2"
                :class="['iconfont']"
                class="loading-map"
                title="加载到地图"
                @click="handleLoadingToMap(scope.row)"
                >&#xe65c;</font
              >
              <div v-if="scope.row.status != 2" class="div-width"></div>
              <!-- <font class="iconfont" title="加载计算成果">&#xe859;</font> -->
              <!-- <span v-if="row.status == 2">
                <img src="@/assets/images/dispatch/ditu.png" @click="handleLoadingToMap(row)" />
              </span> -->
              <font class="iconfont notStart" title="编辑" @click="handleLaishui(scope.row)"
                >&#xe654;</font
              >
              <font
                :class="['iconfont', scope.row.isCheck == 1 ? 'notStart' : 'closeStart']"
                @click="handleJoinExamine(scope.row)"
                :title="scope.row.isCheck == 1 ? '已加入考核' : '未加入考核'"
                >&#xe620;</font
              >

              <font class="iconfont notStart" @click="handleDeleSc(scope.row)" title="删除"
                >&#xe662;</font
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="title">
      <span class="scDtil-font">方案详情</span
      >{{ state.scNameTitle ? '-' + state.scNameTitle : '' }}
    </div>
    <div class="bottom-box">
      <el-tabs v-model="activeName" class="demo-tabs" @tab-change="handleClick">
        <el-tab-pane label="方案属性" name="first">
          <planAttribute
            :scId="state.radio1"
            :showAttribute="props.selectName"
            :zoneId="props.watershedId"
          />
        </el-tab-pane>
        <el-tab-pane label="计算进度" name="second">
          <computProgress
            ref="computProgressRef"
            :scId="state.radio1"
            :computStatus="state.rowStatus"
            @refreshScheme="handleRefreshList"
            :zoneId="props.watershedId"
          />
        </el-tab-pane>
        <el-tab-pane label="分析结果" name="third">
          <computResult
            v-if="activeName == 'third'"
            :scid="state.radio1"
            :watershedId="props.watershedId"
            :scNameObj="state.scNameObj"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
    <!-- 新建、修改弹框 -->
    <planDialog ref="planDialogRef" @handleRefresh="acceptSchemesList" />
    <planDialogDx ref="planDialogDxRef" @handleRefresh="acceptSchemesList" />
    <planDialogImitateRain ref="planDialogImitateRainRef" @handleRefresh="acceptSchemesList" />
    <loadingDialog ref="loadingDialogRef" />
  </div>
</template>

<script setup>
import { reactive, ref, watch, nextTick, onUnmounted } from 'vue'
import {
  getModelRestartSetting,
  saveModelRestartSetting,
  // 查询方案详情
  getDispatchSchemeDetail,
  getDispatchStatusValue,
  getComputSchemeProgress
} from '@/services/modules/dispatch-manage.js'
import emitter from '@/utils/bus'
// 新建，修改
import planDialog from './cpns/planDialog/index.vue'
// 新建修改典型场次
import planDialogDx from './cpns/planDialogDx/index.vue'
// 新建修改模拟降雨
import planDialogImitateRain from './cpns/planDialogImitateRain/index.vue'
// 方案属性
import planAttribute from './cpns/planAttribute/index.vue'
//计算进度
import computProgress from './cpns/computProgress/index.vue'
//计算结果
import computResult from './cpns/computResult/index.vue'
import loadingDialog from './cpns/loadingDialog/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'

import {
  useDispatchManage1,
  useDispatchManageRowIndex,
  useDispatchManageBlkcd
} from '@/store/modules/dispatch-manage.js'
import { storeToRefs } from 'pinia'
import {
  // 查询方案列表
  getDispatchSchemesList,
  //计算接口
  calculateMore,
  //获取四角值
  getDispatchManualSchemeProgSectionExtent,
  // 删除调度方案
  postDeleteDispatchItem,
  // 加入考核
  joinSetCheck
} from '@/services/modules/dispatch-manage.js'
const state = reactive({
  searchName: '',
  scNameObj: {},
  rowStatus: '',
  timer: null,
  statusTimer: null,
  // 方案列表选中行的索引值
  rowIndex: 0,
  modelSchems: [],
  fourAngle: {},
  scid: '',
  radio1: '',
  // 方案列表
  schemeList: [],
  // 方案详情
  schemeDetail: {},
  index: 0,
  // 计算结果显隐
  tabsResult: false
})
const form = reactive({
  restartOnError: false,
  restartInterval: 0,
  restartCount: 0,
  id: ''
})
const dialogVisible = ref(false)
// const tableRef = ref(null);
const planDialogRef = ref(null)
const planDialogDxRef = ref(null)
const planDialogImitateRainRef = ref(null)
const loadingDialogRef = ref(null)
const computProgressRef = ref(null)
const activeName = ref('first')
const props = defineProps({
  watershedId: {
    type: String,
    // 默认大汶河流域
    default: ''
  },
  map: {
    type: Object,
    default: () => {}
  },
  selectName: {
    type: String,
    default: '实测预报降雨'
  }
})
watch(
  () => {
    props.selectName
  },
  async () => {
    // 获取方案列表
    state.schemeList = []

    await acceptSchemesList()

    handleRowClick(state.schemeList[0] || {})
  },
  {
    deep: true,
    immediate: true
  }
)
watch(
  () => {
    props.watershedId
  },
  async () => {
    // 获取方案列表
    await acceptSchemesList()
    // 默认点击第一个方案
    if (state.schemeList) {
      handleRowClick(state.schemeList[0])
      storeToRefs(useDispatchManage1()).watershedId.value = props.watershedId
    } else {
      handleRowClick({})
      storeToRefs(useDispatchManage1()).watershedId.value = ''
    }
  },
  {
    deep: true,
    immediate: true
  }
)

//点击错误重启设置
const handleClickErrorSet = () => {
  getModelRestartSetting().then((res) => {
    form.restartOnError = res.data.isReboot
    form.restartInterval = res.data.rebootTime
    form.restartCount = res.data.rebootNum
    form.id = res.data.id
    dialogVisible.value = true
  })
}
//保存错误重启设置
const handleSaveErrorSet = () => {
  const params = {
    isReboot: form.restartOnError,
    rebootTime: form.restartInterval,
    rebootNum: form.restartCount,
    id: form.id
  }
  saveModelRestartSetting(params).then((res) => {
    dialogVisible.value = false
    ElMessage({
      message: '保存成功',
      type: 'success'
    })
  })
}
//查询方案名称
function handleSearch() {
  acceptSchemesList()
}
// 点击计算进度tab显示图例
function handleClick(val) {
  console.log(val, '计算进度')
  emitter.emit('switchLegend', val)
  computProgressRef.value.whetherLoadingMap(val)
}

// 根据计算状态半段文字颜色
function switchStatusBg(val) {
  switch (val) {
    case 0:
      return 'info'
    case 1:
      return 'primary'
    case 2:
      return 'success'
    case 3:
      return 'lrdata'
    default:
      return 'info'
  }
}
//
function switchStatus(status) {
  switch (status) {
    case 0:
      return '未计算'
    case 1:
      return '计算中'
    case 2:
      return '计算完成'
    case 3:
      return '数据录入'
    default:
      return '未计算'
  }
}
// 点击table某一行
function handleRowClick(row) {
  state.rowStatus = row?.status
  state.scNameTitle = row?.scName
  state.scNameObj = { scNameTitle: state.scNameTitle, type: row.createType }
  // 选中某一行获取当前行的索引值 从0开始
  state.rowIndex = state.schemeList.indexOf(row)
  // 切换到工程预报时 获取当前选中的方案项
  // storeToRefs(useDispatchManageRowIndex()).rowIndex.value = state.schemeList.indexOf(row)
  storeToRefs(useDispatchManageRowIndex()).rowIndex.value = row.id

  state.radio1 = row.id || ''
  storeToRefs(useDispatchManage1()).scidDialog.value = row?.id || ''
  storeToRefs(useDispatchManageBlkcd()).scid.value = row?.id || ''
}

// 新建
function handleLaishui(row) {
  if (props.selectName == '实测预报降雨') {
    planDialogRef.value.handleOpenModal(props.watershedId, row?.id)
  } else if (props.selectName == '典型场次') {
    planDialogDxRef.value.handleOpenModal(props.watershedId, row?.id)
  } else if (props.selectName == '模拟降雨') {
    planDialogImitateRainRef.value.handleOpenModal(props.watershedId, row?.id)
  }
}
// 加载计算成果
function handleLoadingToMap(row) {
  loadingDialogRef.value.handleOpenModal(row)
}
const emit = defineEmits(['computedValue'])
// 点击计算 控制图例显示
async function handleCompute(row, index) {
  state.index = index
  emit('computedValue')
  if (row.id) {
    state.scid = row.id
  }
  // 人工调度方案计算
  calculateMore({ scid: state.scid }).then((res) => {})
  /**
   * 状态轮训
   */

  if (row.createType == '智能预报') {
    state.statusTimer = setInterval(async () => {
      await handleRefreshList()
      if (state.rowStatus == 2) {
        clearInterval(state.statusTimer)
        state.statusTimer = null
      }
    }, 3000)
  } else {
    computProgressRef.value.acceptSchemeDetail(state.scid)
  }

  // await getDispatchSchemeDetail({ scid: row.id, scBelong: 0 }).then((res) => {
  //   if (res.code === 200) {
  //     let { models } = res.data
  //     // 获取子方案（）
  //     state.modelSchems = models.info
  //   }
  // })
  // if (state.modelSchems.length) {
  //   emitter.emit('showProgress', state.modelSchems)
  // }
}

// 获取方案列表
function acceptSchemesList() {
  if (props.selectName == '实测预报降雨') {
    // reportType:0实测+降雨预报
    return new Promise((resolve, reject) => {
      getDispatchSchemesList({
        zoneId: props.watershedId,
        reportType: 0,
        schemeName: state.searchName
      }).then((res) => {
        if (res.code == 200) {
          state.schemeList = res.data
          resolve(state.schemeList)
        }
      })
    })
  } else if (props.selectName == '典型场次') {
    return new Promise((resolve, reject) => {
      getDispatchSchemesList({
        zoneId: props.watershedId,
        reportType: 1,
        schemeName: state.searchName
      }).then((res) => {
        if (res.code == 200) {
          state.schemeList = res.data
          resolve(state.schemeList)
        }
      })
    })
  } else if (props.selectName == '模拟降雨') {
    return new Promise((resolve, reject) => {
      getDispatchSchemesList({
        zoneId: props.watershedId,
        reportType: 3,
        schemeName: state.searchName
      }).then((res) => {
        if (res.code == 200) {
          state.schemeList = res.data
          resolve(state.schemeList)
        }
      })
    })
  }
}
function handleJoinExamine(row) {
  joinSetCheck({ scid: row.id, isCheck: row.isCheck == 1 ? 0 : 1 }).then(async (res) => {
    if (res.code == 200) {
      ElMessage.success('操作成功')
      // 删除成功 重新获取方案列表
      await acceptSchemesList()
      // // 默认选中第一个方案
      handleRowClick(state.schemeList[0])
    }
  })
}
// 删除方案
function handleDeleSc(val) {
  ElMessageBox.confirm(`是否删除`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      postDeleteDispatchItem({ id: val.id }).then(async (res) => {
        if (res.code == 200) {
          ElMessage.success('删除成功')
          // 删除成功 重新获取方案列表
          await acceptSchemesList()
          // 默认选中第一个方案
          handleRowClick(state.schemeList[0])
        } else {
          ElMessage.warning('删除失败')
        }
      })
    })
    .catch(() => {})
}
// 查看计算进度时 刷新列表
async function handleRefreshList() {
  await acceptSchemesList()
  // 仍然选中记录的某一行
  handleRowClick(state.schemeList[state.rowIndex])
}
onUnmounted(() => {})
</script>

<style lang="less" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
.lai-water-box {
  width: 100%;
  height: 100%;
  .pre-box {
    padding: 0 20px;
    height: 460px;
    :deep(.el-table) {
      .el-table__body {
        .el-table__row {
          .el-table_1_column_2 {
            text-align: left !important;
          }
        }
      }
    }
    .info {
      color: #9a9da2;
    }
    .primary {
      color: #4aa3ff;
    }
    .success {
      color: green;
    }
    .lrdata {
      color: blueviolet;
    }
    .title-box {
      display: flex;
      // justify-content: space-between;
      align-items: center;
      height: 50px;
      // padding: 0 20px;
      font-size: var(--header-fontsize);
      border-bottom: 1px solid var(--fold-border-color);
      margin-bottom: 20px;
      .title-right {
        position: absolute;
        right: 20px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .iconfont {
          color: #4ea2ec;
          cursor: pointer;
          margin-right: 30px;
        }
        .loading-map {
          margin-top: -2px !important;
        }

        .iconfont:hover {
          color: #0f83e8;
        }
        .new-file {
          font-size: 30px;
        }
        .search-file {
          font-size: 24px;
        }
      }
      .title-search-box {
        span {
          font-size: 14px;
          margin-left: 10px;
        }
        .el-button {
          margin-left: 10px;
        }
      }
      .handle-box {
        display: flex;
        .iconfont {
          width: 30px;
        }
        .loading-map {
          margin-top: -2px !important;
        }
      }
    }
    .el-table {
      height: calc(100% - 80px);
    }
    .handle-box {
      display: flex;
      .iconfont {
        width: 30px;
      }
      .loading-map {
        margin-top: -2px !important;
      }
      .div-width {
        width: 50px;
        height: 30px;
      }
      // justify-content: space-around;
      img {
        width: 30px;
        height: 30px;
        cursor: pointer;
      }

      .iconfont {
        width: 50px;
        font-size: 24px;
        line-height: 100%;
        font-weight: 400;
        cursor: pointer;
      }
      .loading-map {
        margin-top: -2px !important;
      }

      .notStart {
        color: #0f83e8;
      }
      .closeStart {
        color: #9a9da2;
      }
      .finish {
        color: green;
      }
      // .iconfont:hover {
      //   color: #1ad0095b;
      // }
    }
  }
  .title {
    line-height: 40px;
    margin: 0 20px;
    height: 40px;
    // color: black;
    font-size: var(--header-fontsize);
    // font-weight: 600;
    // font-size: 15px;
    color: #409eff;
    border-bottom: 1px solid var(--fold-border-color);
    margin-bottom: 20px;
    .scDtil-font {
      color: black;
    }
  }
  .bottom-box {
    // padding: 20px;
    padding: 0 20px 0px 20px;
    height: calc(100% - 520px);
    .demo-tabs {
      height: 100%;
      :deep(.el-tabs__header) {
        margin: 0;
        // .el-tabs__item {
        //   padding: 0 30px;
        //   font-size: 14px;
        //   font-weight: 500;
        // }
      }
      :deep(.el-tabs__content) {
        height: calc(100% - 50px);
        .el-tab-pane {
          height: 100%;
        }
      }
    }
  }
}
</style>
